<script lang="ts" setup>
import type {
  TaskSelectedListFetchData,
  TaskResourceFetchData,
  TaskResourceList
} from '@/types/scheduler';

const clusterTypeSelectedListResources = [
  {
    title: '全部',
    value: 0
  },
  {
    title: '云',
    value: 1
  },
  {
    title: '边',
    value: 2
  },
  {
    title: '端',
    value: 3
  }
];

let intervalId: ReturnType<typeof setInterval>;

const clusterType = ref(0);
const clusterSelectedId = ref('');

const taskResourceParams = computed(() => {
  if (clusterSelectedId.value !== '') {
    return {
      type: clusterType.value
    };
  }

  return {
    type: clusterType.value,
    cluster_id: clusterSelectedId.value
  };
});

const taskResources = ref<TaskResourceList>([]);

const { data: clusterListFetchData, execute: clusterListExecute } =
  await useFetch<TaskSelectedListFetchData>(`/api/v1/cluster/list`, {
    params: { type: clusterType } // 动态传递 type 参数
  });

const { data: taskResourceFetchData, execute: taskResourceExecute } =
  useFetch<TaskResourceFetchData>('/api/v1/task/metrics', {
    params: taskResourceParams
  });

watchEffect(() => {
  if (taskResourceFetchData.value === null) {
    taskResources.value = [];
    return;
  }

  const newTaskResources = taskResourceFetchData.value.data.map((task) => ({
    ...task,
    create_at: formatUnixTimestamp(task.create_at)
  }));

  newTaskResources.sort((a, b) => {
    return b.create_at.localeCompare(a.create_at);
  });

  taskResources.value = newTaskResources;
});

const isClusterSelectDisabled = computed(() => {
  return (
    clusterListFetchData === null ||
    clusterListFetchData.value?.data.clusters.length === 0
  );
});

const clusterSelectedListResources = computed(() => {
  if (!clusterListFetchData.value) return [];

  const data = clusterListFetchData.value.data.clusters.map((task: any) => ({
    title: task.name,
    value: task.id
  }));

  return [{ title: '全部', value: '' }].concat(data);
});

// 组件挂载时设置定时器
onMounted(async () => {
  await clusterListExecute();
  await taskResourceExecute();

  intervalId = setInterval(() => {
    taskResourceExecute();
  }, 5000); // 每5秒检查一次
});

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<template>
  <v-container>
    <v-row>
      <v-col>
        <v-select
          v-model="clusterType"
          label="集群类型选择"
          :items="clusterTypeSelectedListResources"
        />
      </v-col>

      <v-col>
        <v-select
          v-model="clusterSelectedId"
          label="集群名选择"
          :disabled="isClusterSelectDisabled"
          :items="clusterSelectedListResources"
        />
      </v-col>
    </v-row>

    <v-row class="mb-4">
      <SchedulerTaskList :data-resources="taskResources" />
    </v-row>
  </v-container>
</template>
